from sqlalchemy import Column, VARCHAR, Integer, ForeignKey
from sqlalchemy.exc import NoResultFound
from sqlalchemy.orm import relationship

from db.base import BaseModel

from db.session import session

from logging import getLogger

log = getLogger("ChatDB")


class Chat(BaseModel):
    __tablename__ = 'chat'
    name = Column(VARCHAR(255), nullable=False, unique=True)
    recipient = Column(VARCHAR(255), nullable=False, unique=True)
    children = relationship("Message", back_populates="parent")

    @classmethod
    def is_unique(cls, chat):
        log.debug(f"Check chat unique {chat.name}")
        try:
            _ = session.query(Chat).filter(cls.recipient == chat.recipient).one()
            _ = session.query(Chat).filter(cls.name == chat.name).one()
        except NoResultFound:
            return True
        else:
            return False
